package com.da.javatest.niuke.jianzhi;

/**
 * @author chenlida
 * @date 2020/10/22 15:28
 * https://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6?
 * tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
 */
public class C31Solution {
    public static int NumberOf1Between1AndN_Solution(int n) {
        int count = 0;
        for (int i = 1; i <= n; i *= 10) {
            int a = n / i, b = n % i;
            //之所以补8，是因为当百位为0，则a/10==(a+8)/10，
            //当百位>=2，补8会产生进位位，效果等同于(a/10+1)
            count += (a + 8) / 10 * i + ((a % 10 == 1) ? b + 1 : 0);
        }
        return count;
    }

    public static int NumberOf1Between1AndN_Solution2(int n) {
        int count = 1;
        for (int i = 10; i <= n; i++) {
            int temp = i;
            while (temp > 0) {
                if (temp % 10 == 1) {
                    count++;
                }
                temp /= 10;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(NumberOf1Between1AndN_Solution(21345));
        System.out.println(NumberOf1Between1AndN_Solution2(21345));
    }
}
